const fs = require('fs');
const path = require('path');
const jsonServer = require('json-server');
const chalk = require('chalk');

const server = jsonServer.create();

server.use(jsonServer.defaults());
// server.use(jsonServer.bodyParser);
//
const base = {};
const dataDir = path.join(__dirname, 'data');
const mockDir = path.join(__dirname, 'mock');

const readData = () => {
	const datafiles = fs.readdirSync(dataDir);
	datafiles.forEach(function(file) {
		Object.assign(base, require(path.resolve(dataDir, file)));
	});
};

readData();

const router = jsonServer.router(base);

//设置增加一个响应头信息“从server到前端”
server.use((req, res, next) => {
	res.header('X-Hello', 'World');
	next();
});

// 数据发送到前端之前包一层
// 返回自定义格式数据
router.render = (req, res) => {
	console.log(res.locals.data);
	res.jsonp({
		//res.locals.data这个是真正的数据
		data: res.locals.data,
		status: 0,
		msg: ''
	});
};

server.use("/api", router);
// server.use(jsonServer.rewriter(rules));
// server.use(router);

const config = global.CONFIG.api;

server.listen({
	port: config.port,
}, function() {
	// console.log(JSON.stringify(jsonServer));
	console.info(chalk.green(`JSON Server is running on port:${config.port}`));
});
